package io.renren.modules.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import io.renren.base.annotation.Login;
import io.renren.common.validator.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;

import io.renren.modules.entity.DetailEntity;
import io.renren.modules.service.DetailService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;


/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-12-01 17:36:58
 */
@RestController
@RequestMapping("api")
@Api(tags = "伤势详细接口")
public class DetailController {
    @Autowired
    private DetailService detailService;

    /**
     * 列表
     */
    @Login
    @PostMapping("detail/list")
    @ApiOperation("列表")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = detailService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */

    @Login
    @PostMapping("detail/info/{goodsId}")
    @ApiOperation("信息")

    public R info(@PathVariable("userId") Long userId) {
        DetailEntity detail = detailService.selectById(userId);

        return R.ok().put("detail", detail);
    }

    /**
     * 保存
     */

//    @Login
    @PostMapping("detail/save")
    @ApiOperation("保存")

    public R save(@RequestBody DetailEntity detail) {
        detailService.insert(detail);
        return R.ok();
    }

    //@Login
    @PostMapping("detail/UploadFile")
    @ApiOperation("上传图片")
    public R UploadFile(HttpServletRequest req, MultipartHttpServletRequest multiReq) {
        // 获取上传文件的路径(原文件的名字)
//        DetailEntity detail,
        String imgFilePath = multiReq.getFile("jpg").getOriginalFilename();
        String voiceFilePath = multiReq.getFile("voice").getOriginalFilename();
        System.out.println(imgFilePath);
        System.out.println("uploadFlePath:" + imgFilePath);
        // 截取上传文件的文件名
//        String uploadFileName = imgFilePath.substring( imgFilePath.lastIndexOf('\\') + 1, imgFilePath.indexOf('.'));
//        String voiceFileName = voiceFilePath.substring( voiceFilePath.lastIndexOf('\\') + 1, voiceFilePath.indexOf('.'));
//        System.out.println("multiReq.getFile()" + uploadFileName);
        // 截取上传文件的后缀
        String imgFileSuffix = imgFilePath.substring(imgFilePath.indexOf('.') + 1, imgFilePath.length());
        String voiceFileSuffix = voiceFilePath.substring(voiceFilePath.indexOf('.') + 1, voiceFilePath.length());
//        System.out.println("uploadFileSuffix:" + imgFileSuffix);
        FileOutputStream imgFos = null;
        FileInputStream imgFis = null;

        FileOutputStream voiceFos = null;
        FileInputStream voiceFis = null;

        try {
            String path = "D://Program Files//apache-tomcat-8.0.3//webapps//xiaomuyiFile//";
//            String path = "D:/apache-tomcat-8.0.3/webapps/xiaomuyiFile";
            //上传的照片或视频
            imgFis = (FileInputStream) multiReq.getFile("jpg").getInputStream();
            File file = new File(path);
            if (file == null || !file.exists()) {
                file.mkdirs();
            }
            long timestamp = System.currentTimeMillis();
            imgFos = new FileOutputStream(file + "/" + timestamp + "." + imgFileSuffix);

            byte[] temp = new byte[1024];
            int i = imgFis.read(temp);
            while (i != -1) {
                imgFos.write(temp, 0, temp.length);
                imgFos.flush();
                i = imgFis.read(temp);
            }
//上传的录音
            String voicePath = null;
            if (voiceFileSuffix.equals("arm")) {

                voiceFis = (FileInputStream) multiReq.getFile("voice").getInputStream();
                voiceFos = new FileOutputStream(file + "/" + timestamp + "." + voiceFileSuffix);
                byte[] voiceTemp = new byte[1024];
                int j = voiceFis.read(voiceTemp);
                while (j != -1) {
                    voiceFos.write(voiceTemp, 0, voiceTemp.length);
                    voiceFos.flush();
                    j = voiceFis.read(voiceTemp);
                }
                voicePath = "xiaomuyiFile/" + +timestamp + "." + voiceFileSuffix;
            }
            DetailEntity detailEntity = new DetailEntity();
            String jpgPath = "xiaomuyiFile/" + +timestamp + "." + imgFileSuffix;

            //
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


            detailEntity.setDisease(req.getParameter("disease"));
            detailEntity.setImg(jpgPath);
            detailEntity.setVoice(voicePath);
            detailEntity.setCreateTime(df.format(new Date()));
            detailEntity.setUserId(req.getParameter("userId"));

            detailService.insert(detailEntity);
            return R.ok();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (imgFis != null) {
                try {
                    imgFis.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (imgFos != null) {
                try {
                    imgFos.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (voiceFis != null) {
                try {

                    voiceFis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (voiceFos != null) {
                try {

                    voiceFos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        http:
//10.129.50.212/jpg/
        return null;
    }

    /**
     * 修改
     */
//    @Login
    @PostMapping("detail/update")
    @ApiOperation("修改")

    public R update(@RequestBody DetailEntity detail) {
        ValidatorUtils.validateEntity(detail);
        detailService.updateAllColumnById(detail);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @Login
    @PostMapping("detail/delete")
    @ApiOperation("删除")
    public R delete(@RequestBody Long[] userIds) {
        detailService.deleteBatchIds(Arrays.asList(userIds));

        return R.ok();
    }

}
